package com.example.boot.derived;

import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class DerivedVariable {

    private final Set<String> dependencyIds; // 依赖的原子变量ID集合
    private final DerivationCalculator calculator;
    private final AtomVariableRepository repository;

    public DerivedVariable(Set<String> dependencyIds,
                           DerivationCalculator calculator,
                           AtomVariableRepository repository) {
        this.dependencyIds = dependencyIds;
        this.calculator = calculator;
        this.repository = repository;

        dependencyIds.forEach(id -> {
            if (!repository.exists(id)) { // 新增exists方法
                throw new MissingDependencyException(id);
            }
        });
    }

    public double compute() {
        Map<String, Double> inputs = dependencyIds.stream()
                .collect(Collectors.toMap(
                        id -> id,
                        id -> repository.getValue(id)
                                .orElseThrow(() -> new MissingDependencyException(id))
                ));
        return calculator.calculate(inputs);
    }
}
